package com.wangcang.widgetlibrary.http;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.wangcang.widgetlibrary.activity.base.MobileApplication;
import com.wangcang.widgetlibrary.activity.constant.Constant;
import com.wangcang.widgetlibrary.bean.CommonClass;
import com.yolanda.nohttp.Binary;
import com.yolanda.nohttp.FileBinary;
import com.yolanda.nohttp.Headers;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.OnUploadListener;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.download.DownloadListener;
import com.yolanda.nohttp.download.DownloadRequest;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/10/7.
 */

public class NoHttpUtils {
    private static String mBaseUrl = "";

    private static final int REQUEST_FAIL = -1;    //请求失败
    private static final int REQUEST_SUCCESS = 1;  //请求成功
    private static final int REQUEST_FINISH = 2;   //请求完成

    public static Request<byte[]> getByteRequest(String url, Map params, RequestMethod requestMethod) {
        String env = MobileApplication.sp.getValue(Constant.sp_Env, Constant.ENV_DEFAULT);

        if (Constant.ENV_DEV.equals(env)) {
            mBaseUrl = Constant.URL_BASE_DEV;
        } else if (Constant.ENV_CIT.equals(env)) {
            mBaseUrl = Constant.URL_BASE_CIT;
        } else if (Constant.ENV_SIT.equals(env)) {
            mBaseUrl = Constant.URL_BASE_SIT;
        } else if (Constant.ENV_UAT.equals(env)) {
            mBaseUrl = Constant.URL_BASE_UAT;
        } else if (Constant.ENV_RELEASE.equals(env)) {
            mBaseUrl = Constant.URL_BASE_RELEASE;
        }

        String jsonString = JSON.toJSONString(params);

        String urlString = mBaseUrl + url + "?data=" + jsonString;

        String uriString = "";

        try {
            URL urlObject = new URL(urlString);
            URI uriObject = new URI(urlObject.getProtocol(), urlObject.getHost() + ":" + urlObject.getPort(), urlObject.getPath(), urlObject.getQuery(), null);
            uriString = uriObject.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        Log.i("请求的地址：", uriString);

        // 创建请求对象
        Request<byte[]> request = NoHttp.createByteArrayRequest(uriString, requestMethod);

        //添加头信息
        String token = MobileApplication.sp.getValue(Constant.sp_Token);

        //auth_token必须传，不能为""，先随便写一个值
        if (!TextUtils.isEmpty(token)) {
            request.addHeader("auth_token", token);
        } else {
            request.addHeader("auth_token", "10000");
        }

        request.addHeader("sign", "");
        request.addHeader("version", "1.0"); //服务端api版本
        request.addHeader("charset", "UTF-8");
        request.addHeader("w_appid", "wh_android_" + MobileApplication.getApplicationInstance().getVersionName());  //客户端版本描述

//        request.setDefineRequestBodyForJson(jsonString); // 添加参数
        request.setConnectTimeout(10 * 1000); // 设置连接超时
        request.setReadTimeout(20 * 1000); // 设置读取超时时间，也就是服务器的响应超时

        return request;
    }

    // 第二个参数取值RequestMethod.POST   RequestMethod.GET
    private static Request<String> getRequest(String url, Map params, RequestMethod requestMethod) {
        Map map = new HashMap();

        String versionName = MobileApplication.getApplicationInstance().getVersionName();

        if (requestMethod == RequestMethod.POST) {
            url = url + "?t=" + System.currentTimeMillis() + "&w_appid=" + "wh_android" + "&version=v" + versionName + "&method=" + "acPay.financialPay";

            // 以map的形式添加请求参数
            map.put("data", params);
            map.put("notify_url", "");
            map.put("format", "json");
        } else if (requestMethod == RequestMethod.GET) {
            String jsonString = JSON.toJSONString(params);

            // 请求参数直接添加到url后面
            url = url + "?t=" + System.currentTimeMillis() + "&w_appid=" + "wh_android_" + versionName + "&data=" + jsonString;
        }

        String jsonString = JSON.toJSONString(map);

        Log.i("请求的地址：", url);
        Log.i("请求的参数：", jsonString);

        // 创建请求对象
        Request<String> request = NoHttp.createStringRequest(url, requestMethod);

        //添加头信息
        String token = MobileApplication.sp.getValue(Constant.sp_Token);

        //auth_token必须传，不能为""，先随便写一个值
        if (!TextUtils.isEmpty(token)) {
            request.addHeader("auth_token", token);
        } else {
            request.addHeader("auth_token", "10000");
        }

        request.addHeader("sign", "");
        request.addHeader("version", "1.0"); //服务端api版本
        request.addHeader("charset", "UTF-8");
        request.addHeader("w_appid", "wh_android_" + MobileApplication.getApplicationInstance().getVersionName());  //客户端版本描述
        request.addHeader("method", "acPay.financialPay");  //方法名

        request.setDefineRequestBodyForJson(jsonString); // 添加参数
        request.setConnectTimeout(10 * 1000); // 设置连接超时
        request.setReadTimeout(20 * 1000); // 设置读取超时时间，也就是服务器的响应超时

        return request;
    }

    // 普通的Get Post请求的回调监听
    public interface OnResponseListener {
        void onSucceed(CommonClass commonClass, int what);

        void onFailed(String result, int what);

        void onFinish(int what);
    }


    // Get请求
    public static void httpGet(final String url, final Map params, final OnResponseListener responseListener, final int w) {

        String env = MobileApplication.sp.getValue(Constant.sp_Env, Constant.ENV_DEFAULT);

        if (Constant.ENV_DEV.equals(env)) {
            mBaseUrl = Constant.URL_BASE_DEV;
        } else if (Constant.ENV_CIT.equals(env)) {
            mBaseUrl = Constant.URL_BASE_CIT;
        } else if (Constant.ENV_SIT.equals(env)) {
            mBaseUrl = Constant.URL_BASE_SIT;
        } else if (Constant.ENV_UAT.equals(env)) {
            mBaseUrl = Constant.URL_BASE_UAT;
        } else if (Constant.ENV_RELEASE.equals(env)) {
            mBaseUrl = Constant.URL_BASE_RELEASE;
        }

        final String newUrl = mBaseUrl + url;

        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                int what = msg.what;

                if (what == REQUEST_SUCCESS) {
                    // 请求成功
                    if (responseListener != null) {
                        String resultString = (String) msg.obj;

                        CommonClass commonClass = JSON.parseObject(resultString, CommonClass.class);

                        if ("4".equals(commonClass.getCode())) {

                            return;
                        }

                        responseListener.onSucceed(commonClass, w);
                    }
                } else if (what == REQUEST_FINISH) {
                    // 请求完成
                    if (responseListener != null) {
                        responseListener.onFinish(w);
                    }
                } else {
                    if (responseListener != null) {
                        // 请求失败
                        responseListener.onFailed((String) msg.obj, w);
                    }
                }
            }
        };

        if (NetUtils.isHttpConnected(MobileApplication.getApplicationInstance())) {
            ThreadUtils.newThread(new Runnable() {
                @Override
                public void run() {
                    Request<String> request = getRequest(newUrl, params, RequestMethod.GET);
                    Response<String> response = NoHttp.startRequestSync(request);
                    String resultString = response.get();

                    Log.i("请求的结果：", resultString);

                    handler.sendEmptyMessage(REQUEST_FINISH); // 请求完成

                    if ((response.getHeaders().getResponseCode() + "").startsWith("2")) {
                        // 请求成功
                        Message msg = new Message();
                        msg.what = REQUEST_SUCCESS;
                        msg.obj = resultString;
                        handler.sendMessage(msg);
                    } else {
                        // 请求失败
                        Message msg = new Message();
                        msg.what = REQUEST_FAIL;
                        msg.obj = resultString;
                        handler.sendMessage(msg);
                    }
                }
            });
        } else {
            // 没联网，直接完成
            handler.sendEmptyMessage(REQUEST_FINISH); // 请求完成

            // 请求失败
            Message msg = new Message();
            msg.what = REQUEST_FAIL;
            msg.obj = "no net";
            handler.sendMessage(msg);
        }
    }

    // Get请求
    public static void httpPost(final String url, final Map params, final OnResponseListener responseListener, final int w) {

        String env = MobileApplication.sp.getValue(Constant.sp_Env, Constant.ENV_DEFAULT);

        if (Constant.ENV_DEV.equals(env)) {
            mBaseUrl = Constant.URL_BASE_DEV;
        } else if (Constant.ENV_CIT.equals(env)) {
            mBaseUrl = Constant.URL_BASE_CIT;
        } else if (Constant.ENV_SIT.equals(env)) {
            mBaseUrl = Constant.URL_BASE_SIT;
        } else if (Constant.ENV_UAT.equals(env)) {
            mBaseUrl = Constant.URL_BASE_UAT;
        } else if (Constant.ENV_RELEASE.equals(env)) {
            mBaseUrl = Constant.URL_BASE_RELEASE;
        }
        final String nu;
//        if(w == 2){
//            nu = "http://192.168.200.90:8070/" + url;
//        }else{
        nu = mBaseUrl + url;
//        }
        final String newUrl = nu;
        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                int what = msg.what;

                if (what == REQUEST_SUCCESS) {
                    // 请求成功
                    if (responseListener != null) {
                        String resultString = (String) msg.obj;

                        CommonClass commonClass = JSON.parseObject(resultString, CommonClass.class);

                        if ("4".equals(commonClass.getCode())) {

                            return;
                        }

                        responseListener.onSucceed(commonClass, w);
                    }
                } else if (what == REQUEST_FINISH) {
                    // 请求完成
                    if (responseListener != null) {
                        responseListener.onFinish(w);
                    }
                } else {
                    // 请求失败
                    if (responseListener != null) {
                        responseListener.onFailed((String) msg.obj, w);
                    }
                }
            }
        };

        if (NetUtils.isHttpConnected(MobileApplication.getApplicationInstance())) {
            ThreadUtils.newThread(new Runnable() {
                @Override
                public void run() {
                    Request<String> request = getRequest(newUrl, params, RequestMethod.POST);
                    Response<String> response = NoHttp.startRequestSync(request);
                    String resultString = response.get();

                    Log.i("请求的结果：", resultString);

                    handler.sendEmptyMessage(REQUEST_FINISH); // 请求完成

                    if ((response.getHeaders().getResponseCode() + "").startsWith("2")) {
                        // 请求成功
                        Message msg = new Message();
                        msg.what = REQUEST_SUCCESS;
                        msg.obj = resultString;
                        handler.sendMessage(msg);
                    } else {
                        // 请求失败
                        Message msg = new Message();
                        msg.what = REQUEST_FAIL;
                        msg.obj = resultString;
                        handler.sendMessage(msg);
                    }
                }
            });
        } else {
            // 没联网，直接完成
            handler.sendEmptyMessage(REQUEST_FINISH); // 请求完成

            // 请求失败
            Message msg = new Message();
            msg.what = REQUEST_FAIL;
            msg.obj = "no net";
            handler.sendMessage(msg);
        }
    }

    // 组拼get参数, 不过没用上
    private static String getUrl(String url, HashMap<String, String> params) {
        // 添加url参数
        if (params != null) {
            Iterator<String> it = params.keySet().iterator();

            StringBuffer stringBuffer = null;

            while (it.hasNext()) {
                String key = it.next();
                String value = params.get(key);

                if (stringBuffer == null) {
                    stringBuffer = new StringBuffer();
                    stringBuffer.append("?");
                } else {
                    stringBuffer.append("&");
                }

                stringBuffer.append(key);
                stringBuffer.append("=");
                stringBuffer.append(value);
            }

            url += stringBuffer.toString();
        }

        return url;
    }


}
